package com.cn.wanxi.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBC {
    private static final String URL = "jdbc:mysql://121.199.55.96:3306/cy04?serverTimezone=PRC";
    private static final String USER = "cy04";
    private static final String PASSWORD = "123456";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    private static CallableStatement callableStatement = null;//创建CallableStatement对象
    private static Connection conn = null;
    private static PreparedStatement pst = null;
    private static ResultSet rst = null;

    private static Connection getConnection() {
        try {
            // 加载数据库驱动程序
            try {
                Class.forName(DRIVER);
            } catch (ClassNotFoundException e) {
                System.out.println("加载驱动错误");
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
            // 获取连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return conn;
    }

    /**
     * insert update delete SQL语句的执行的统一方法
     *
     * @param sql  SQL语句
     * @param para 参数数组，若没有参数则为null
     * @return 受影响的行数
     */
    public static int executeUpdate(String sql, Object para) {
        // 受影响的行数
        int affectedLine = 0;
        List<Object> params = getPara(para);
        try {
            // 获得连接
            conn = getConnection();
            // 调用SQL
            pst = conn.prepareStatement(sql);

            // 参数赋值
            if (params != null) {
                for (int i = 0; i < params.size(); i++) {
                    pst.setObject(i + 1, params.get(i));
                }
            }
//            System.out.println(pst);
            // 执行
            affectedLine = pst.executeUpdate();

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            // 释放资源
            closeAll();
        }
        return affectedLine;
    }

    /**
     * SQL 查询将查询结果直接放入ResultSet中
     *
     * @param sql  SQL语句
     * @param para 参数数组，若没有参数则为null
     * @return 结果集
     */
    private static ResultSet executeQueryRS(String sql, Object para) {
        try {
            // 获得连接
            conn = getConnection();
            // 调用SQL
            pst = conn.prepareStatement(sql);
            List<Object> params = getPara(para);
            // 参数赋值
            if (params != null) {
                for (int i = 0; i < params.size(); i++) {
                    pst.setObject(i + 1, params.get(i));
                }
            }
            System.out.println(pst);
            // 执行
            rst = pst.executeQuery();

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return rst;
    }

    /**
     * 获取结果集，并将结果放在List中
     *
     * @param sql   SQL语句
     * @param prams 参数数组，若没有参数则为null
     * @return List
     * 结果集
     */
    public static List<Map> excuteQuery(String sql, Object prams) {
        // 执行SQL获得结果集
        ResultSet rs = executeQueryRS(sql, prams);

        // 创建ResultSetMetaData对象
        ResultSetMetaData rsmd = null;

        // 结果集列数
        int columnCount = 0;
        try {
            rsmd = rs.getMetaData();

            // 获得结果集列数
            columnCount = rsmd.getColumnCount();
        } catch (SQLException e1) {
            System.out.println(e1.getMessage());
        }
        // 创建List
        List<Map> list = new ArrayList<>();

        try {
            // 将ResultSet的结果保存到List中
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    map.put(rsmd.getColumnLabel(i), rs.getObject(i));
                }
                list.add(map);//每一个map代表一条记录，把所有记录存在list中
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            // 关闭所有资源
            closeAll();
        }

        return list;
    }

    /**
     * 将传递过来的参数封装成数组
     *
     * @param object
     * @return
     */
    private static List<Object> getPara(Object object) {
//        String[] strings = object.toString().split(",");
//        List<Object> list = new ArrayList<>(Arrays.asList(strings));
        //以下代码可以用上面两行代替
        List<Object> list = new ArrayList<>();
        if (object == null || object.toString().equals("")) return null;
        String[] strings = object.toString().split(",");
        for (int i = 0; i < strings.length; i++) {
            list.add(strings[i]);
        }
        return list;
    }

    /**
     * 关闭所有资源
     */
    private static void closeAll() {
        // 关闭结果集对象
        try {
            if (rst != null) {
                rst.close();
            }

            // 关闭PreparedStatement对象
            if (pst != null) {
                pst.close();
            }

            // 关闭CallableStatement 对象
            if (callableStatement != null) {
                callableStatement.close();

            }

            // 关闭Connection 对象
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

    }
}
